package com.pjc.db;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.DataSources;
import java.sql.Connection;

/**
 * MYSQL底层类
 * 
 * @author 王畅
 * @since 2015年6月21日
 */
public class MySqlConn {

	private static MySqlConn instance;
	private String dburl = "";
	private String logname = "";
	private String logpwd = "";
	public ComboPooledDataSource ds;

	private void initCpds() throws Exception {

		ds = new ComboPooledDataSource();
		ds.setDriverClass("com.mysql.jdbc.Driver");
		ds.setJdbcUrl(this.dburl);
		ds.setUser(this.logname);
		ds.setPassword(this.logpwd);
		ds.setAutoCommitOnClose(false);
		ds.setMaxPoolSize(20);
		ds.setTestConnectionOnCheckin(true);
		ds.setIdleConnectionTestPeriod(120);
		ds.setPreferredTestQuery("SELECT 1;");

	}

	public void init(String dbUrl, String userName, String pwd) throws Exception {
		this.dburl = dbUrl;
		this.logname = userName;
		this.logpwd = pwd;
		initCpds();
	}

	public static final MySqlConn getInstance() {
		synchronized (MySqlConn.class) {
			if (instance == null)
				instance = new MySqlConn();
		}
		return instance;
	}

	public synchronized final Connection getConn() throws Exception {
		if (this.ds == null) {
			initCpds();
		}
		return this.ds.getConnection();
	}

	protected void finalize() throws Throwable {
		DataSources.destroy(ds);
		super.finalize();
	}
}